const myHost = process.env.NODE_ENV === 'development' ? 'http://192.168.0.6' : location.origin ;

function get(serviceName, data, success, error) {
	reqesut(serviceName, data, success, error , 'GET');
}

function post(serviceName, data, success, error) {
	reqesut(serviceName, data, success, error , 'POST');
}

function reqesut(serviceName, data, success, error , method){
	var jsonData = {};
	for(var key in data){
		if ( !!data[key] || data[key] == false || data[key] == 0 ) {
			jsonData[key] = data[key] ;
		}else{
			jsonData[key] = "" ;
		}
	}
	var token = uni.getStorageSync("token");
	// jsonData['token'] = token ;
	// jsonData['X-Requested-With'] = "XMLHttpRequest";
	uni.request({
		url: myHost + serviceName ,
		method: method ,
		data: jsonData ,
		header:{
			"token" : token ,
			"X-Requested-With" : "XMLHttpRequest"
		},
		success: res => {
			var data = res.data ;
			if (data.state == "needLogin") {
				var href = getPageRoute();
				uni.setStorageSync("beforeLoginPage" , href);
				uni.removeStorageSync("token");
				uni.redirectTo({
					url: "/pages/login/login"
				});
			}else if(data.state == "noAuth"){
				uni.showModal({
					title:'提示',
					content:'无操作权限,请联系管理员',
					confirmColor:'#5d83f7',
					showCancel:false ,
					success : function(e){
						uni.removeStorageSync("token");
						uni.removeStorageSync("beforeLoginPage");
						uni.reLaunch({
							url:"/pages/login/login"
						});
					}
				});
			}else if(data.state == "ok" || !data.state ){
				success(data) ;
			}else{
				if (typeof error == 'function') {
					error(data) ;
				}else{
					showTips(data.err);
				}
			}
			uni.stopPullDownRefresh();
		},
		fail: () => {
			uni.showToast({
				title: '服务不可用',
				icon : 'none'
			});
			uni.hideLoading();
			uni.stopPullDownRefresh();
		},
		complete: () => {
			
		}
	});
}

function showTips(tip){
	if(tip && tip.length > 10){
		uni.showModal({
			title:'提示',
			content: tip ,
			showCancel:false,
			confirmColor:'#5d83f7'
		});
	}else{
		uni.showToast({
			title: tip ,
			icon : 'none'
		});
	}
}

function appendParams(url){
	var appendData = {
		"token" : uni.getStorageSync("token"),
		'X-Requested-With' : "XMLHttpRequest"
	};
	var params = toParams(appendData);
	url += url.indexOf("?") > -1 ? "&" : "?" ;
	url += params ;
	return url ;
}

function uploadFile(url , filePath , success){
	url = appendParams(url) ;
	const task = uni.uploadFile({
		url:  myHost + url ,
		filePath: filePath ,
		name : 'upfile' ,
		header:{
			"token" : uni.getStorageSync("token")
		},
		success:function(res){
			var data = JSON.parse(res.data);
			uni.hideLoading();
			if (data.state == "needLogin") {
				uni.redirectTo({
					url:"/pages/login/login"
				});
			}else{
				if (typeof success == "function") {
					success(data);
				}
			}
		},
		fail:function(e){
			uni.hideLoading();
			uni.showToast({
				title: '上传失败',
				icon : 'none'
			});
		}
	});
	task.onProgressUpdate((res) => {
		uni.showLoading({
			title: res.progress + "%",
			mask:true
		})
	});
	
	return task ;
}


//请求参数字符串化
function paramsToString(jsonData){
	for(var key in jsonData){
		jsonData[key] = jsonData[key] + "" ;
	}
	return jsonData ;
}

//验证密码，数字、字母组合
const pswReg = /^(\w){6,20}$/;
function regPsw(psw) {
	return !!psw && pswReg.test(psw);
}



//时间戳格式化为日期
function formatDate(timestamp) {
	var now = new Date(parseFloat(timestamp));
	var year = now.getFullYear();
	var month = formatMinNum(now.getMonth() + 1);
	var date = formatMinNum(now.getDate());
	var hour = formatMinNum(now.getHours());
	var minute = formatMinNum(now.getMinutes());
	var second = formatMinNum(now.getSeconds());
	return year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second;
}

//日期格式化为年月日
function formatDays(date) {
	var now =  date || new Date();
	var year = now.getFullYear();
	var month = formatMinNum(now.getMonth() + 1);
	var date = formatMinNum(now.getDate());
	var hour = formatMinNum(now.getHours());
	var minute = formatMinNum(now.getMinutes());
	var second = formatMinNum(now.getSeconds());
	return year + "-" + month + "-" + date ;
}

function formatMinNum(num){
	return num > 9 ? num : "0" + num ;
}

//格式化数字
function formatNum(num){
	if (num < 100000) {
		return (num+"").replace( /\B(?=(?:\d{3})+$)/g, ',' );
	}
	var wanNum = parseFloat(num/10000).toFixed(2);
	if (wanNum < 1000) {
		var str = wanNum + "" ;
		var intSum = str.substring(0,str.indexOf(".")).replace( /\B(?=(?:\d{3})+$)/g, ',' );//取到整数部分
		var dot = str.substring(str.length,str.indexOf(".")) ;//取到小数部分搜索
		return (wanNum+"").replace( /\B(?=(?:\d{3})+$)/g, ',' ) + '万';
	}
	wanNum = parseInt(num/10000) ;
	return (wanNum+"").replace( /\B(?=(?:\d{3})+$)/g, ',' ) + "万";
} 

//json转参数
function toParams(jsonData , filterKeys){
	var params = [] ;
	for(var key in jsonData){
		if (!!filterKeys && filterKeys.indexOf(key) > -1) {
			continue ;
		}
		var value = jsonData[key] ;
		value = value == 'null' || value == null ? '' : value ;
		params.push(key + "=" + value);
	}
	return params.join('&');
}

//返回历史页面
function goBack( defaultPage , index){
	index = index || 1 ;
	var pageList = getCurrentPages();
	if (pageList.length <= index) {
		defaultPage = defaultPage || '/pages/index/index' ;
		defaultPage = defaultPage && defaultPage.indexOf("/pages/") == -1 ? "/pages/" + defaultPage + "/" + defaultPage : defaultPage ;
		uni.navigateTo({
			url: defaultPage 
		});
	}else{
		uni.navigateBack({
			delta: index
		});
	}
}

function getCurPage(){
    var pages = getCurrentPages();
    return pages[pages.length-1];
}

function getPageRoute(e){
	/*获取当前路由*/
	let curPage = getCurPage();
	var route = "/" + curPage.route ;
	//在微信小程序或是app中，通过curPage.options；如果是H5，则需要curPage.$route.query（H5中的curPage.options为undefined）
	let curParam = curPage.options || curPage.$route.query;
	var params = toParams(curParam) ;
	return params ? route + "?" + params : route ;
}

function getPage(url , success){
	var that = getCurPage();
	var data = that.conditions || {} ;
	var page = that.page ;
	data['pageNumber'] = page.pageNumber ;
	data['pageSize'] = page.pageSize ;
	get(url , data , function(res){
		that.page = res.page ;
		if (typeof success == "function") {
			success(res) ;
		}
		that.loading = false ;
	});
}

function getList(url , success){
	var that = getCurPage();
	var data = that.conditions || {} ;
	get(url , data , function(res){
		that.list = res.list ;
		that.loading = false ;
		if (typeof success == "function") {
			success() ;
		}
	});
}

function checkHasAuth(menuList , url){
	for (var i = 0; i < menuList.length; i++) {
		var cur = menuList[i];
		if (cur.url == url) {
			return true ;
		}
	}
	return false ;
}

//验证url无请求权限
function hasAuth(url){
	var menuList = getApp().globalData.menuList ;
	if (menuList.length > 0) {
		return checkHasAuth(menuList , url);
	}
	var that = this ;
	var data = {} ;
	get("/admin/globalData",data,function(res){
		getApp().globalData.menuList = res.menuList ;
		getApp().globalData.admin = res.admin ;
		checkHasAuth(res.menuList , url);
	});
}

function download(url){
	url = appendParams(url) ;
	console.log(myHost +url);
	location.href = myHost + url ;
}

export default {
	reqesut,
	get,
	post,
	uploadFile,
	regPsw ,
	formatDate ,
	formatDays ,
	paramsToString ,
	toParams ,
	formatNum ,
	goBack ,
	myHost ,
	getPageRoute ,
	getPage ,
	getList ,
	hasAuth ,
	download,
	showTips
}
